import { login } from '@/services/loginApi';
import { encryptWithSHA256 } from '@/utils/crypto';
import { setToken } from '@/utils/authInterceptor';
import { setUserInfo } from '@/utils/cookieUtils';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginFormPage, ProConfigProvider, ProFormText } from '@ant-design/pro-components';
import { history, useModel, useRequest } from '@umijs/max';
import { Button, Divider, GlobalToken, message, theme } from 'antd';

const getActivityConfig = (token: GlobalToken) => {
  return {
    style: {
      boxShadow: '0px 0px 8px rgba(0, 0, 0, 0.2)',
      color: token.colorTextHeading,
      borderRadius: 8,
      backgroundColor: 'rgba(255,255,255,0.25)',
      backdropFilter: 'blur(4px)',
    },
    title: '活动标题，可配置图片',
    subTitle: '活动介绍说明文字',
    action: (
      <Button
        size="large"
        style={{
          borderRadius: 20,
          background: token.colorBgElevated,
          color: token.colorPrimary,
          width: 120,
        }}
      >
        去看看
      </Button>
    ),
  };
};

const LoginPage = () => {
  const { token } = theme.useToken();
  const { initialState, refresh } = useModel('@@initialState');

  const requestLogin = useRequest(login, {
    manual: true,
    loadingDelay: 300,
    onSuccess: async (data) => {
      if (data && data.token && data.userInfo) {
        console.log("token",data.token);
        
        // 保存token到localStorage和cookie，设置7天过期
        setToken(data.token, 7);

        // 保存用户信息到cookie，设置7天过期
        setUserInfo(data.userInfo, 7);

        message.success('登录成功');

        // 登录成功后刷新全局状态（不再需要额外请求用户信息）
        try {
          await refresh();
          // 跳转到仪表盘
          history.replace('/dashboard');
        } catch (error) {
          console.error('刷新全局状态失败:', error);
          // 即使刷新失败，也跳转到仪表盘
          // history.replace('/dashboard');
        }
      } else {
        message.error('登录失败：未获取到有效token或用户信息');
      }
    },
    onError: (error: any) => {
      console.error('登录失败:', error);
      const errorMessage = error?.message || '登录失败，请检查用户名和密码';
      message.error(errorMessage);
    },
  });

  return (
    <div style={{ height: '100vh' }}>
      <LoginFormPage
        backgroundImageUrl="https://mdn.alipayobjects.com/huamei_gcee1x/afts/img/A*y0ZTS6WLwvgAAAAAAAAAAAAADml6AQ/fmt.webp"
        logo="https://github.githubassets.com/images/modules/logos_page/Octocat.png"
        backgroundVideoUrl="https://gw.alipayobjects.com/v/huamei_gcee1x/afts/video/jXRBRK_VAwoAAAAAAAAAAAAAK4eUAQBr"
        title="推普活动管理系统"
        containerStyle={{
          backgroundColor: 'rgba(0, 0, 0,0.65)',
          backdropFilter: 'blur(4px)',
        }}
        subTitle="推普活动H5项目后台管理系统"
        activityConfig={getActivityConfig(token)}
        actions={
          <div>
            <Divider plain>
              <span
                style={{
                  color: token.colorTextPlaceholder,
                  fontWeight: 'normal',
                  fontSize: 14,
                }}
              >
                忘记密码？请联系管理员
              </span>
            </Divider>
          </div>
        }
        onFinish={async (values) => {
          try {
            // 对密码进行SHA-256加密
            const encryptedPassword = encryptWithSHA256(values.password);

            // 构建登录参数，符合API文档格式
            const loginParams: LOGIN.LoginParams = {
              username: values.username,
              password: encryptedPassword
            };

            // 发送登录请求
            await requestLogin.run(loginParams);
            return true;
          } catch (error) {
            console.error('登录过程出错:', error);
            // 错误信息已在onError中处理，这里不重复显示
            return false;
          }
        }}
      >
        <ProFormText
          name="username"
          width="md"
          fieldProps={{
            size: 'large',
            prefix: <UserOutlined />,
          }}
          placeholder={'用户名'}
          rules={[
            {
              required: true,
              message: '请输入用户名!',
            },
            {
              min: 3,
              message: '用户名至少3个字符',
            },
          ]}
        />
        <ProFormText.Password
          name="password"
          width="md"
          fieldProps={{
            size: 'large',
            prefix: <LockOutlined />,
          }}
          placeholder={'密码'}
          rules={[
            {
              required: true,
              message: '请输入密码！',
            },
            {
              min: 6,
              message: '密码至少6个字符',
            },
          ]}
        />
      </LoginFormPage>
    </div>
  );
};

export default () => {
  return (
    <ProConfigProvider dark>
      <LoginPage />
    </ProConfigProvider>
  );
};
